using McpApi.Models;
using System.Text.Json;

namespace McpApi.Services
{
    /// <summary>
    /// MES工具服务 - 从LangChain移植并适配MCP
    /// </summary>
    public class MESToolService
    {
        private readonly ILogger<MESToolService> _logger;
        private readonly HttpClient _httpClient;
        private readonly IConfiguration _configuration;

        public MESToolService(ILogger<MESToolService> logger, HttpClient httpClient, IConfiguration configuration)
        {
            _logger = logger;
            _httpClient = httpClient;
            _configuration = configuration;

            // 配置HTTP客户端
            var baseUrl = _configuration["MESServices:BaseUrl"] ?? "http://localhost:5001";
            _httpClient.BaseAddress = new Uri(baseUrl);
            _httpClient.Timeout = TimeSpan.FromSeconds(30);

            // 配置认证头（如果需要）
            var apiKey = _configuration["MESServices:ApiKey"];
            if (!string.IsNullOrEmpty(apiKey))
            {
                _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
            }
        }

        /// <summary>
        /// 查询生产订单 - 调用SqlsugarService API
        /// </summary>
        public async Task<MESToolResult> QueryProductionOrdersAsync(Dictionary<string, object> parameters)
        {
            try
            {
                _logger.LogInformation("开始查询生产订单");

                // 构建MES工具执行请求
                var toolRequest = new
                {
                    ToolName = "query_production_orders",
                    Parameters = parameters,
                    UserId = "mcp_user",
                    RequestId = Guid.NewGuid().ToString()
                };

                var requestJson = JsonSerializer.Serialize(toolRequest);
                var content = new StringContent(requestJson, System.Text.Encoding.UTF8, "application/json");

                // 调用SqlsugarService的MES工具执行API
                var response = await _httpClient.PostAsync("/api/MESAssistant/execute-tool", content);

                if (response.IsSuccessStatusCode)
                {
                    var responseJson = await response.Content.ReadAsStringAsync();
                    var apiResult = JsonSerializer.Deserialize<JsonElement>(responseJson);

                    _logger.LogInformation("成功调用SqlsugarService获取生产订单数据");

                    return new MESToolResult
                    {
                        Success = true,
                        Message = "查询生产订单成功",
                        Data = apiResult.GetProperty("result")
                    };
                }
                else
                {
                    _logger.LogWarning("SqlsugarService API调用失败，状态码: {StatusCode}，使用模拟数据", response.StatusCode);
                    var fallbackData = GenerateMockProductionOrders(
                        parameters.GetValueOrDefault("orderId")?.ToString(),
                        parameters.GetValueOrDefault("status")?.ToString(),
                        int.Parse(parameters.GetValueOrDefault("pageSize")?.ToString() ?? "10")
                    );

                    return new MESToolResult
                    {
                        Success = true,
                        Message = "查询生产订单成功（备用数据）",
                        Data = new { orders = fallbackData, total = fallbackData.Count }
                    };
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询生产订单失败");
                return new MESToolResult
                {
                    Success = false,
                    Message = $"查询失败: {ex.Message}",
                    ErrorCode = "QUERY_ERROR"
                };
            }
        }

        /// <summary>
        /// 查询物料库存 - 调用SqlsugarService API
        /// </summary>
        public async Task<MESToolResult> QueryMaterialInventoryAsync(Dictionary<string, object> parameters)
        {
            try
            {
                _logger.LogInformation("开始查询物料库存");

                // 构建MES工具执行请求
                var toolRequest = new
                {
                    ToolName = "query_material_inventory",
                    Parameters = parameters,
                    UserId = "mcp_user",
                    RequestId = Guid.NewGuid().ToString()
                };

                var requestJson = JsonSerializer.Serialize(toolRequest);
                var content = new StringContent(requestJson, System.Text.Encoding.UTF8, "application/json");

                // 调用SqlsugarService的MES工具执行API
                var response = await _httpClient.PostAsync("/api/MESAssistant/execute-tool", content);

                if (response.IsSuccessStatusCode)
                {
                    var responseJson = await response.Content.ReadAsStringAsync();
                    var apiResult = JsonSerializer.Deserialize<JsonElement>(responseJson);

                    _logger.LogInformation("成功调用SqlsugarService获取物料库存数据");

                    return new MESToolResult
                    {
                        Success = true,
                        Message = "查询物料库存成功",
                        Data = apiResult.GetProperty("result")
                    };
                }
                else
                {
                    _logger.LogWarning("SqlsugarService API调用失败，状态码: {StatusCode}，使用模拟数据", response.StatusCode);
                    var fallbackData = GenerateMockInventory(
                        parameters.GetValueOrDefault("materialCode")?.ToString(),
                        parameters.GetValueOrDefault("materialName")?.ToString(),
                        parameters.GetValueOrDefault("warehouseCode")?.ToString()
                    );

                    return new MESToolResult
                    {
                        Success = true,
                        Message = "查询物料库存成功（备用数据）",
                        Data = new { inventory = fallbackData, total = fallbackData.Count }
                    };
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询物料库存失败");
                return new MESToolResult
                {
                    Success = false,
                    Message = $"查询失败: {ex.Message}",
                    ErrorCode = "QUERY_ERROR"
                };
            }
        }

        /// <summary>
        /// 查询BOM信息 - 从LangChain移植
        /// </summary>
        public async Task<MESToolResult> QueryBOMInfoAsync(Dictionary<string, object> parameters)
        {
            try
            {
                await Task.CompletedTask; // 保持异步方法签名
                _logger.LogInformation("开始查询BOM信息");

                var productCode = parameters.GetValueOrDefault("productCode")?.ToString();
                var version = parameters.GetValueOrDefault("version")?.ToString() ?? "1.0";

                // 模拟数据
                var mockData = GenerateMockBOM(productCode, version);

                return new MESToolResult
                {
                    Success = true,
                    Message = "查询成功",
                    Data = mockData
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询BOM信息失败");
                return new MESToolResult
                {
                    Success = false,
                    Message = $"查询失败: {ex.Message}",
                    ErrorCode = "QUERY_ERROR"
                };
            }
        }




        /// <summary>
        /// 生成生产报表 - 从LangChain移植
        /// </summary>
        public async Task<MESToolResult> GenerateProductionReportAsync(Dictionary<string, object> parameters)
        {
            try
            {
                await Task.CompletedTask; // 保持异步方法签名
                _logger.LogInformation("开始生成生产报表");

                var reportType = parameters.GetValueOrDefault("reportType")?.ToString() ?? "daily";
                var startDate = DateTime.Parse(parameters.GetValueOrDefault("startDate")?.ToString() ?? DateTime.Today.ToString());
                var endDate = DateTime.Parse(parameters.GetValueOrDefault("endDate")?.ToString() ?? DateTime.Today.ToString());

                // 模拟报表数据
                var mockReport = GenerateMockReport(reportType, startDate, endDate);

                return new MESToolResult
                {
                    Success = true,
                    Message = "报表生成成功",
                    Data = mockReport
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成生产报表失败");
                return new MESToolResult
                {
                    Success = false,
                    Message = $"生成失败: {ex.Message}",
                    ErrorCode = "REPORT_ERROR"
                };
            }
        }

        #region 模拟数据生成方法

        private List<object> GenerateMockProductionOrders(string? orderId, string? status, int pageSize)
        {
            var orders = new List<object>();
            var statuses = new[] { "待开始", "进行中", "已完成", "已暂停" };
            var random = new Random();

            for (int i = 1; i <= Math.Min(pageSize, 5); i++)
            {
                var currentOrderId = orderId ?? $"PO{DateTime.Now:yyyyMMdd}{i:D3}";
                var currentStatus = status ?? statuses[random.Next(statuses.Length)];

                orders.Add(new
                {
                    orderId = currentOrderId,
                    productName = $"产品{(char)('A' + i - 1)}",
                    productCode = $"PROD{i:D3}",
                    status = currentStatus,
                    quantity = random.Next(100, 1000),
                    completedQuantity = random.Next(0, 500),
                    progress = random.Next(0, 100),
                    startDate = DateTime.Today.AddDays(-random.Next(1, 30)),
                    planEndDate = DateTime.Today.AddDays(random.Next(1, 15)),
                    workshop = $"车间{i}"
                });
            }

            return orders;
        }

        private List<object> GenerateMockInventory(string? materialCode, string? materialName, string? warehouseCode)
        {
            var inventory = new List<object>();
            var random = new Random();

            for (int i = 1; i <= 3; i++)
            {
                inventory.Add(new
                {
                    materialCode = materialCode ?? $"MAT{i:D3}",
                    materialName = materialName ?? $"物料{i}",
                    warehouseCode = warehouseCode ?? $"WH{i:D2}",
                    warehouseName = $"仓库{i}",
                    currentStock = random.Next(50, 500),
                    availableStock = random.Next(30, 400),
                    reservedStock = random.Next(0, 50),
                    unit = "件",
                    lastUpdateTime = DateTime.UtcNow.AddMinutes(-random.Next(1, 60))
                });
            }

            return inventory;
        }

        private object GenerateMockBOM(string? productCode, string version)
        {
            return new
            {
                productCode = productCode ?? "PROD001",
                productName = "示例产品",
                version = version,
                status = "有效",
                materials = new[]
                {
                    new { materialCode = "MAT001", materialName = "原料A", quantity = 2, unit = "件" },
                    new { materialCode = "MAT002", materialName = "原料B", quantity = 1, unit = "套" },
                    new { materialCode = "MAT003", materialName = "原料C", quantity = 3, unit = "个" }
                },
                createTime = DateTime.UtcNow.AddDays(-30),
                updateTime = DateTime.UtcNow.AddDays(-5)
            };
        }

        private object GenerateMockReport(string reportType, DateTime startDate, DateTime endDate)
        {
            var random = new Random();
            return new
            {
                reportType = reportType,
                period = new { startDate, endDate },
                summary = new
                {
                    totalOrders = random.Next(50, 200),
                    completedOrders = random.Next(30, 150),
                    inProgressOrders = random.Next(10, 50),
                    totalOutput = random.Next(1000, 5000),
                    efficiency = Math.Round(random.NextDouble() * 30 + 70, 2)
                },
                details = Enumerable.Range(1, 5).Select(i => new
                {
                    date = startDate.AddDays(i - 1),
                    orders = random.Next(5, 20),
                    output = random.Next(100, 500),
                    efficiency = Math.Round(random.NextDouble() * 20 + 75, 2)
                }).ToArray(),
                generateTime = DateTime.UtcNow
            };
        }

        #endregion
    }
}
